<template>
  <div class="container fade-in">
    <div class="header">
      <h2 class="section-title">系统日志</h2>
    </div>

    <!-- 筛选条件 -->
    <div class="card filters slide-up" style="animation-delay: 0.1s">
      <div class="filter-row">
        <div class="field">
          <label>日志类型</label>
          <select v-model="activeLogType" @change="handleLogTypeChange" class="select">
            <option value="action">操作日志</option>
            <option value="error">错误日志</option>
          </select>
        </div>
        <div class="field">
          <label>开始时间</label>
          <DateField v-model="queryParams.startTime" mode="datetime" />
        </div>
        <div class="field">
          <label>结束时间</label>
          <DateField v-model="queryParams.endTime" mode="datetime" />
        </div>
        <div class="field">
          <label>关键字</label>
          <input 
            type="text" 
            v-model="queryParams.key" 
            placeholder="搜索关键字"
            class="input"
            @input="debouncedSearch"
          />
        </div>
        <div class="field">
          <button @click="handleSearch" class="btn primary">
            <span class="icon">🔍</span>
            查询
          </button>
        </div>
        <div class="field">
          <button @click="exportLogs" class="btn secondary">
            <span class="icon">�</span>
            导出
          </button>
        </div>
      </div>
    </div>

    <!-- 操作日志表格 -->
    <div v-if="activeLogType === 'action'" class="card table-container slide-up" style="animation-delay: 0.2s">
      <div class="table-header">
        <h3>操作日志</h3>
        <div class="table-actions">
          <button @click="refreshLogs" class="btn secondary">
            <span class="icon">🔄</span>
            刷新
          </button>
        </div>
      </div>
      
      <div class="table-wrapper">
        <table class="table">
          <thead>
            <tr>
              <th>操作人</th>
              <th>操作类型</th>
              <th>操作内容</th>
              <th>IP地址</th>
              <th>操作结果</th>
              <th>操作时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-if="loading" class="loading-row">
              <td colspan="7" class="loading">
                <div class="spinner"></div>
                加载中...
              </td>
            </tr>
            <tr v-else-if="actionLogs.length === 0" class="empty-row">
              <td colspan="7" class="empty">暂无数据</td>
            </tr>
            <template v-else>
              <tr v-for="log in actionLogs" :key="`action-${log.id}`" class="data-row">
                <td>{{ log.userId || '-' }}</td>
                <td>{{ log.type || '-' }}</td>
                <td class="action-content">{{ log.action || '-' }}</td>
                <td>{{ log.ip || '-' }}</td>
                <td>
                  <span :class="['badge', getResultColor(log.result)]">
                    {{ getResultText(log.result) }}
                  </span>
                </td>
                <td>{{ formatLogTime(log.creationTime) }}</td>
                <td>
                  <button @click="viewLogDetail(log)" class="btn small secondary">
                    <span class="icon">👁️</span>
                    详情
                  </button>
                </td>
              </tr>
            </template>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 错误日志表格 -->
    <div v-if="activeLogType === 'error'" class="card table-container slide-up" style="animation-delay: 0.2s">
      <div class="table-header">
        <h3>错误日志</h3>
        <div class="table-actions">
          <button @click="refreshLogs" class="btn secondary">
            <span class="icon">🔄</span>
            刷新
          </button>
        </div>
      </div>
      
      <div class="table-wrapper">
        <table class="table">
          <thead>
            <tr>
              <th>用户</th>
              <th>错误信息</th>
              <th>API接口</th>
              <th>IP地址</th>
              <th>发生时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-if="loading" class="loading-row">
              <td colspan="6" class="loading">
                <div class="spinner"></div>
                加载中...
              </td>
            </tr>
            <tr v-else-if="errorLogs.length === 0" class="empty-row">
              <td colspan="6" class="empty">暂无数据</td>
            </tr>
            <template v-else>
              <tr v-for="log in errorLogs" :key="`error-${log.id}`" class="data-row">
                <td>{{ log.userId || '-' }}</td>
                <td class="error-message">{{ log.message || '-' }}</td>
                <td>{{ log.api || '-' }}</td>
                <td>{{ log.ip || '-' }}</td>
                <td>{{ formatLogTime(log.creationTime) }}</td>
                <td>
                  <button @click="viewLogDetail(log)" class="btn small secondary">
                    <span class="icon">👁️</span>
                    详情
                  </button>
                </td>
              </tr>
            </template>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination slide-up" style="animation-delay: 0.3s">
      <div class="pagination-info">
        共 {{ pagination.total }} 条记录，第 {{ pagination.current }} / {{ Math.ceil(pagination.total / pagination.pageSize) }} 页
      </div>
      <div class="pagination-controls">
        <button 
          @click="changePage(pagination.current - 1)" 
          :disabled="pagination.current <= 1"
          class="btn secondary"
        >
          上一页
        </button>
        <span class="page-numbers">
          <button 
            v-for="page in getPageNumbers()" 
            :key="page"
            @click="changePage(page)"
            :class="['btn', page === pagination.current ? 'primary' : 'secondary']"
            :disabled="page === -1"
          >
            {{ page === -1 ? '...' : page }}
          </button>
        </span>
        <button 
          @click="changePage(pagination.current + 1)" 
          :disabled="pagination.current >= Math.ceil(pagination.total / pagination.pageSize)"
          class="btn secondary"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 日志详情弹窗 -->
    <div v-if="showDetailModal" class="modal-overlay" @click="closeDetailModal">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>日志详情</h3>
          <button @click="closeDetailModal" class="btn close">✕</button>
        </div>
        <div class="modal-body">
          <div v-if="selectedLog" class="log-detail">
            <div v-for="(value, key) in selectedLog" :key="key" class="detail-item">
              <label>{{ getFieldLabel(key) }}:</label>
              <div class="detail-value">{{ formatDetailValue(key, value) }}</div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="closeDetailModal" class="btn secondary">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import DateField from '../components/DateField.vue'
import { 
  LogService, 
  type LogQueryRequest, 
  type ActionLog, 
  type ErrorLog,
  formatLogTime,
  getResultText,
  getResultColor
} from '../services/log'

// 响应式数据
const activeLogType = ref<'action' | 'error'>('action')
const loading = ref(false)
const showDetailModal = ref(false)
const selectedLog = ref<ActionLog | ErrorLog | null>(null)

// 查询参数
const queryParams = reactive<LogQueryRequest>({
  pageIndex: 1,
  pageSize: 20,
  startTime: '',
  endTime: '',
  key: ''
})

// 分页信息
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0
})

// 日志数据缓存
const logCache = new Map<string, { data: any[], total: number, timestamp: number }>()
const CACHE_DURATION = 5 * 60 * 1000 // 5分钟缓存

// 日志数据
const actionLogs = ref<ActionLog[]>([])
const errorLogs = ref<ErrorLog[]>([])

// 计算属性 - 当前显示的日志列表
const currentLogs = computed(() => {
  return activeLogType.value === 'action' ? actionLogs.value : errorLogs.value
})

// 防抖搜索
const debounce = (func: Function, delay: number) => {
  let timeoutId: ReturnType<typeof setTimeout>
  return (...args: any[]) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => func.apply(null, args), delay)
  }
}

const debouncedSearch = debounce(() => {
  pagination.current = 1
  searchLogs()
}, 500)

// 将显示值（YYYY-MM-DD HH:mm[:ss] 或 带T分隔）转为接口需要的 ISO 字符串
function formatDateTimeForQuery(dateTimeStr: string) {
  if (!dateTimeStr) return ''
  const m = dateTimeStr.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2}))?$/)
  if (m) {
    const [, y, mo, d, h, min, s] = m
    return `${y}-${mo}-${d}T${h}:${min}:${s || '00'}`
  }
  const d = new Date(dateTimeStr)
  if (!isNaN(d.getTime())) {
    const pad = (n: number) => String(n).padStart(2, '0')
    return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
  }
  return dateTimeStr
}

// 初始化时间范围（默认最近7天）
const initTimeRange = () => {
  const now = new Date()
  const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)

  const formatDisplayDateTime = (date: Date) => {
    const pad = (n: number) => String(n).padStart(2, '0')
    const y = date.getFullYear()
    const m = pad(date.getMonth() + 1)
    const d = pad(date.getDate())
    const h = pad(date.getHours())
    const i = pad(date.getMinutes())
    const s = pad(date.getSeconds())
    return `${y}-${m}-${d} ${h}:${i}:${s}`
  }

  queryParams.endTime = formatDisplayDateTime(now)
  queryParams.startTime = formatDisplayDateTime(sevenDaysAgo)
}

// 切换日志类型
const handleLogTypeChange = () => {
  pagination.current = 1
  searchLogs()
}

// 处理搜索
const handleSearch = () => {
  pagination.current = 1
  searchLogs()
}

// 搜索日志
const searchLogs = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      limit: pagination.pageSize,
      startTime: formatDateTimeForQuery(queryParams.startTime),
      endTime: formatDateTimeForQuery(queryParams.endTime),
      key: queryParams.key || ''
    }
    
    let response
    switch (activeLogType.value) {
      case 'action':
        response = await LogService.getActionLogs(params)
        if (response.code === 0 && response.data) {
          actionLogs.value = response.data.data || []
          pagination.total = response.data.total || 0
        }
        break
      case 'error':
        response = await LogService.getErrorLogs(params)
        if (response.code === 0 && response.data) {
          errorLogs.value = response.data.data || []
          pagination.total = response.data.total || 0
        }
        break
    }
  } catch (error) {
    console.error('获取日志失败:', error)
  } finally {
    loading.value = false
  }
}

// 刷新日志
const refreshLogs = () => {
  searchLogs()
}

// 导出日志
const exportLogs = () => {
  // TODO: 实现日志导出功能
  alert('导出功能开发中...')
}

// 切换页码
const changePage = (page: number) => {
  if (page < 1 || page > Math.ceil(pagination.total / pagination.pageSize) || page === -1) return
  pagination.current = page
  searchLogs()
}

// 获取页码数组
const getPageNumbers = () => {
  const totalPages = Math.ceil(pagination.total / pagination.pageSize)
  const current = pagination.current
  const pages: number[] = []
  
  if (totalPages <= 7) {
    for (let i = 1; i <= totalPages; i++) {
      pages.push(i)
    }
  } else {
    if (current <= 4) {
      for (let i = 1; i <= 5; i++) {
        pages.push(i)
      }
      pages.push(-1) // 省略号
      pages.push(totalPages)
    } else if (current >= totalPages - 3) {
      pages.push(1)
      pages.push(-1) // 省略号
      for (let i = totalPages - 4; i <= totalPages; i++) {
        pages.push(i)
      }
    } else {
      pages.push(1)
      pages.push(-1) // 省略号
      for (let i = current - 1; i <= current + 1; i++) {
        pages.push(i)
      }
      pages.push(-1) // 省略号
      pages.push(totalPages)
    }
  }
  
  return pages
}

// 查看日志详情
const viewLogDetail = (log: ActionLog | ErrorLog) => {
  selectedLog.value = log
  showDetailModal.value = true
}

// 关闭详情弹窗
const closeDetailModal = () => {
  showDetailModal.value = false
  selectedLog.value = null
}

// 获取字段标签
const getFieldLabel = (key: string): string => {
  const labels: Record<string, string> = {
    id: 'ID',
    userId: '用户ID',
    type: '类型',
    action: '操作动作',
    version: '版本',
    apiUrl: 'API地址',
    ip: 'IP地址',
    params: '参数',
    result: '结果',
    resultMessage: '结果信息',
    creationTime: '创建时间',
    message: '错误信息',
    api: 'API'
  }
  return labels[key] || key
}

// 格式化详情值
const formatDetailValue = (key: string, value: any): string => {
  if (value === null || value === undefined) return '-'
  
  if (key === 'creationTime') {
    return formatLogTime(value)
  }
  
  if (key === 'result') {
    return getResultText(value)
  }
  
  if (key === 'params' && typeof value === 'string') {
    try {
      return JSON.stringify(JSON.parse(value), null, 2)
    } catch {
      return value
    }
  }
  
  return String(value)
}

// 组件挂载时初始化
onMounted(() => {
  initTimeRange()
  searchLogs()
})
</script>

<style scoped>
.action-content {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.error-message {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.log-detail {
  max-height: 400px;
  overflow-y: auto;
}

.detail-item {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid var(--border-light);
}

.detail-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.detail-item label {
  font-weight: 600;
  color: var(--text-secondary);
  display: block;
  margin-bottom: 5px;
}

.detail-value {
  background: var(--bg-light);
  padding: 8px 12px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  white-space: pre-wrap;
  word-break: break-all;
}

.badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.badge.success {
  background: var(--success-light);
  color: var(--success);
}

.badge.danger {
  background: var(--danger-light);
  color: var(--danger);
}

.badge.secondary {
  background: var(--bg-light);
  color: var(--text-secondary);
}
</style>
